package br.com.emersondeandrade.aplicacao.mobile.controllers;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import br.com.emersondeandrade.aplicacao.mobile.CookiesService;
import br.com.emersondeandrade.modelo.core.casa.Casa;
import br.com.emersondeandrade.modelo.core.casa.CasaFacade;
import br.com.emersondeandrade.modelo.exeption.ObjectNaoEncontradoExeption;


@Controller
@Scope("request")
@RequestMapping(value = "/mobile")
public class RegistrarMobileController {

	
	
	
	@Autowired
	CasaFacade casaFacade;
	

	
	@RequestMapping(value = "/registra",method = RequestMethod.POST)
	public ModelAndView registraMobile(@RequestParam("key") String key, HttpServletResponse response){		
		
		Casa casa = null;
		try {
			 casa = casaFacade.getCasaByKeyArduino( key );
		} catch (ObjectNaoEncontradoExeption e) {
			return new ModelAndView("registrarMobile","erro","Codigo invalido");
			
		}
			
		// grava cookie
		Cookie cookie = new Cookie(CookiesService.COOKIE_NAME, casaFacade.geraHashMobile(key) );
		cookie.setMaxAge( 60*60*24*300 );// 1 ano para expirar
		response.addCookie(cookie);
		
		return new ModelAndView("painelControle","casa", casa );
		
	}
		
		
	
	@RequestMapping(value = "/verificaKey",method = RequestMethod.GET)
	public ModelAndView verificaKey(HttpServletRequest r){
	
		Casa casa = null;
		
		String jsp = "registrarMobile";
		
		String hash = CookiesService.getValue(CookiesService.COOKIE_NAME, r.getCookies());
		 				
		try {
			 casa = casaFacade.getCasaByKeyArduino( casaFacade.descriptografaHashMobile(hash)  );
			 jsp = "painelControle";
		} catch (ObjectNaoEncontradoExeption e) {
			 return new ModelAndView(jsp);
		}
			
	
		
		
		return new ModelAndView(jsp,"casa",casa);
		
		
	}
	
	
}
